package com.yuan.java.yzm;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片切割工具类
 *
 * @author Johnson
 * @version Friday June 10th, 2011
 */
public class CutImage {
    /**
     * 切割图片
     *
     * @param sourceFile 源文件
     */
    public List<InputStream> cut(File sourceFile, int num)
            throws Exception {
        List<InputStream> list = new ArrayList<>();
        BufferedImage source = ImageIO.read(sourceFile);
        int sWidth = source.getWidth(); // 图片宽度
        int width = sWidth / num;
        int sHeight = source.getHeight(); // 图片高度
        int height = sHeight;
        if (sWidth >= width) {
            int cols = 0; // 横向切片总数  
            int rows = 0; // 纵向切片总数  
            int eWidth = 0; // 末端切片宽度  
            int eHeight = 0; // 末端切片高度  
            if (sWidth % width == 0) {
                cols = sWidth / width;
            } else {
                eWidth = sWidth % width;
                cols = sWidth / width + 1;
            }
            if (sHeight % height == 0) {
                rows = sHeight / height;
            } else {
                eHeight = sHeight % height;
                rows = sHeight / height + 1;
            }
            BufferedImage image = null;
            int cWidth = 0; // 当前切片宽度  
            int cHeight = 0; // 当前切片高度  
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    cWidth = getWidth(j, cols, eWidth, width);
                    cHeight = getHeight(i, rows, eHeight, height);
                    // x坐标,y坐标,宽度,高度  
                    image = source.getSubimage(j * width, i * height, cWidth,
                            cHeight);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ImageIO.write(image, "png", os);
                    InputStream is = new ByteArrayInputStream(os.toByteArray());
                    list.add(is);
                }
            }
        }
        return list;
    }

    /**
     * 获取当前切片的宽度
     */
    private int getWidth(int index, int cols, int endWidth, int width) {
        if (index == cols - 1) {
            if (endWidth != 0) {
                return endWidth;
            }
        }
        return width;
    }

    /**
     * 获取当前切片的高度
     */
    private int getHeight(int index, int rows, int endHeight, int height) {
        if (index == rows - 1) {
            if (endHeight != 0) {
                return endHeight;
            }
        }
        return height;
    }
}  